package com.lxy.service;

import com.lxy.dto.LoginDto;
import com.lxy.entity.BackendUser;
import com.lxy.entity.DevUser;
import com.lxy.mapper.BackendUserDao;
import com.lxy.mapper.DevUserDao;
import com.lxy.util.SessionUtils;
import com.lxy.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class LoginService {
    @Autowired
    DevUserDao devUserDao;
    @Autowired
    BackendUserDao backendUserDao;
    public LoginVo login(LoginDto loginDto) {
        LoginVo loginVo  = new LoginVo();
        if(loginDto.getUserType()==1){
            //管理员
            BackendUser devUser = new BackendUser();
            devUser.setUsercode(loginDto.getAccount());
            devUser.setUserpassword(loginDto.getPassword());
            List<BackendUser> devUsers = backendUserDao.queryAllBy(devUser);
            if(devUsers.size()==0){
                throw new RuntimeException("账号密码错误");
            }
            //生成token
            String token = UUID.randomUUID().toString().replace("-","");
            token+="-"+loginDto.getUserType();
            token+="-"+devUsers.get(0).getId();
            token+="-"+System.currentTimeMillis();

            loginVo.setToken(token);
            loginVo.setAccount(devUsers.get(0).getUsercode());
            loginVo.setLoginType(loginDto.getUserType());

            SessionUtils.add(token,devUsers.get(0));
        }else if(loginDto.getUserType()==2){
            //开发者
            DevUser devUser = new DevUser();
            devUser.setDevcode(loginDto.getAccount());
            devUser.setDevpassword(loginDto.getPassword());
            List<DevUser> devUsers = devUserDao.queryAllBy(devUser);
            if(devUsers.size()==0){
                throw new RuntimeException("账号密码错误");
            }
            //生成token
            String token = UUID.randomUUID().toString().replace("-","");
            token+="-"+loginDto.getUserType();
            token+="-"+devUsers.get(0).getId();
            token+="-"+System.currentTimeMillis();

            loginVo.setToken(token);
            loginVo.setAccount(devUsers.get(0).getDevcode());
            loginVo.setLoginType(loginDto.getUserType());

            SessionUtils.add(token,devUsers.get(0));
        }else {
            throw new RuntimeException("类型错误");
        }
        return loginVo;
    }
}
